import React, { useState, useEffect } from 'react';
import classNames from 'classnames';
import './index.less';

const timeOrderList = ['24', '96'];
const TjTimeOrderSelect: React.FC<ITjTimeOrderSelectProps> = (props) => {
  const [value, setValue] = useState<string>('24');
  const [index, setIndex] = useState<number>(0);

  const onChange = (v: string) => {
    if (props.onChange) {
      props.onChange(v);
    } else {
      setIndex(timeOrderList.indexOf(v));
      setValue(v);
    }
  };

  useEffect(() => {
    if (props.value) {
      setIndex(timeOrderList.indexOf(props.value));
      setValue(props.value);
    }
  }, [props.value]);

  return (
    <div className="tj-time-order-select">
      <div className="active" style={{ left: `${6 + index * 28}px` }} />
      {timeOrderList.map((v) => {
        return (
          <div
            key={v}
            className={classNames('item', { 'item-active': value === v })}
            onClick={() => onChange(v)}
          >
            {v}
          </div>
        );
      })}
    </div>
  );
};

interface ITjTimeOrderSelectProps {
  onChange?: (value: string) => void;
  value?: string;
}

export default TjTimeOrderSelect;
